var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var FileStore = require('session-file-store')(session);
var webUploader = require('node-webuploader-server');
var uploaderConfig = { uploadDir: path.join(__dirname, 'public', 'uploads'), limitExtension: null };
var favicon = require('serve-favicon');
var config = require('./config');
var morgan = require('morgan');
var router = express.Router();
var fs = require('fs');
var app = express();

app.set('views', './views');
app.set('view engine', 'jade');
app.locals.pretty = config.pretty;

// 静态资源请求路径
app.use(express.static(path.join(__dirname, config.debug ? "public/" : "dist/")));
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//body-parser 解析json格式数据
app.use(bodyParser.json({ limit: '3mb' }));
//此项必须在 bodyParser.json 下面,为参数编码
app.use(bodyParser.urlencoded({
	extended: true
}));

app.use(session({
	name:'keydone',
	resave: false,										// 是否每次都重新保存会话，建议false
    secret: 'keydone',									// 用来对session id相关的cookie进行签名
	cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},			// 设置cookie有效期
	saveUninitialized: false,							// 是否自动保存未初始化的会话，建议false
	store: new FileStore()								// 本地存储session（文本文件，也可以选择其他store，比如redis等）
}));

var uploder = new webUploader(uploaderConfig);
uploder.mount(router);
app.use('/upload', router);

app.listen(config.port);

console.log("服务器已启动,端口是" + config.port);

require('./router')(app)

// 捕获 404 并进行错误处理
app.use(function (req, res, next) {
	var err = new Error('Not Found');
	err.status = 404;
	next(err);
});

if (app.get('env') === 'development') {
	app.set('showStackError', true);
	app.use(morgan(':method :url :status'));
	app.use(function (err, req, res, next) {
		res.status(err.status || 500);
		res.render('error', {
			message: err.message,
			error: err
		});
	});
}

module.exports = app;